<template>
  <div class="stats-panel stats-panel-trend" ref="trend">
    <div class="stats-panel-head stats-form">
      <h3>{{ $t('report.performanceChart.name') }}
        <el-popover trigger="hover">
          <ul>
            <li>{{ $t('report.performanceChart.tips1') }}</li>
            <li>{{ $t('report.performanceChart.tips2') }}</li>
          </ul>
          <stats-popover-icon slot="reference"></stats-popover-icon>
        </el-popover>
      </h3>
      <!-- <div class="stats-form-group">
        <select id="team" @change="chooseTeam">
          <option value="">全部</option>
          <option v-for="team in teams" :key="team.id" :value="team.id">{{team.name}}</option>
        </select>
      </div> -->
      <biz-team-select class="stats-team-select biz-team-select" is-auto-select-child collapse multiple :value="tag" @input="chooseTeam" :fetch-func="fetchTeam"/>
      <div class="stats-form-group">
        <!-- <div id="date-range" class="stats-form-daterange">
          <span>{{trendStartTime}} - {{trendEndTime}}</span> 
          <b class="caret"></b>
        </div> -->
        <date-picker @datePicker="datePicker" />
      </div>
    </div>
    <div class="stats-panel-body">
      <div id="trend"></div>
    </div>

    <div class="stats-trend-table-wrap" v-show="showTable">
      <div class="stats-trend-table-bar">
        <h5>{{ $t('common.label.taskList') }}</h5>

        <button class="btn btn-primary btn-sm" @click="exportData" style="margin-right: 5px;" v-if="isButtonDisplayed">
          {{ $t('common.base.export') }}
        </button>
        <button class="btn btn-primary btn-sm" @click="exportAllData" style="margin-right: 5px;" v-if="isButtonDisplayed">
        {{ $t('common.base.exportAll') }}
        </button>
        <button class="btn btn-primary btn-sm" @click="showTable = false">
        {{ $t('common.base.hide') }}
        </button>
      </div>
      <base-table class="stats-table"
                  :rows="tableData.list || []" 
                  :columns="columns"
                  :disable-select="true"
                  :limit="10"
      ></base-table>
    </div>
  </div>
</template>

<script>
/* global moment, _init_data*/
import { isOpenData, openAccurateTab } from '@src/util/platform';

import _ from 'lodash';
import qs from 'src/util/querystring';
import http from 'src/util/HttpUtil';

import echarts from 'packages/Echarts'

import TaskStateEnum from '@model/enum/TaskStateEnum';
import { checkButtonDisplayed } from '@src/util/dom';
let trend = null;
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { t } from '@src/locales'
import { dayTimeStart, dayTimeEnd, rangeOfDay } from 'pub-bbx-utils';
export default {
  name: 'performance-chart',
  data(){
    return {
      isButtonDisplayed: checkButtonDisplayed(),
      isOpenData,
      tag: [],
      // teams: [],
      trendStartTime: '',
      trendEndTime: '',
      teamId: '',
      tableData: {},
      columns: this.buildColumns(),
      showTable: false,
      state: '',
      day: ''
    };
  },
  methods: {
    fetchTeam(params){
      return http.post('/security/tag/tree', {...params, ...{authKey: 'VIP_REPORT_VIEW'}})
    },
    exportAllData(){
      let model = {
        exportAll: '1',
        tagId: this.teamId
      }

      if(this.trendStartTime) model.timeStart = this.trendStartTime;
      if(this.trendEndTime) model.timeEnd = this.trendEndTime;
      window.location.href = `/api/report/outside/stats/plan/trendDetail/export?${ qs.stringify(model)}`;
    },
    exportData(){
      let model = {
        state: this.state,
        tagId: this.teamId
      }

      if(this.day){
        const [timeStart, timeEnd] = rangeOfDay(this.day)
        model.timeStart = +timeStart;
        model.timeEnd = +timeEnd;
      } 
      
      window.location.href = `/api/report/outside/stats/plan/trendDetail/export?${ qs.stringify(model)}`;
    },
    chooseDate(start, end) {
      this.$emit('trackEvent', 'chooseDate');
      
      this.trendStartTime = start;
      this.trendEndTime = end;
      this.renderTrend();
    },
    chooseTeam(value){
      this.$emit('trackEvent', 'chooseTeam');

      // let tag = (Array.isArray(value) ? value[0] : value) || {};
      let tag = value
      this.tag = value;
      this.teamId = tag.map(item => {return item.id}).join(',');
      this.renderTrend();
    },
    initTrend(start, end) {
      trend = echarts.init(document.getElementById('trend'));
      trend.on('click', event => {
        if(event.data.value == 0) return;

        let origin = event.data._origin;
        let state = 'created';
        let day = origin.days;

        if(event.seriesName == t('task.setting.taskTypeSetting.flow.flowMap.finish.name')) state = 'finished';

        this.state = state;
        this.day = day;

        this.renderTable(day, state);
      });
      
      this.trendStartTime = start;
      this.trendEndTime = end;
      this.renderTrend();
    },
    async renderTrend() {
      try{
        this.showTable = false;
        let instance = this.$loading.show(this.$el)

        let data = await this.fetchTrendData();
        instance.hide();

        trend.clear();
        trend.setOption(this.getTrendOption(data.created, data.completed))
      }catch(err){
        console.log(err)
      }
    },
    getTrendOption(created, completed){
      let colors = ['#5793f3', this.getThemeColor, '#675bba'];

      let created_xAxis = [];
      let created_data = [];
      created.forEach(item =>{
        created_xAxis.push(item.days)
        created_data.push({
          name: t('report.callConsultChart.addWorkOrder'),
          value: item.count,
          _origin: item
        })
      });

      let completed_xAxis = [];
      let completed_data = [];
      completed.forEach(item =>{
        completed_xAxis.push(item.days);
        completed_data.push({
          name: t('task.setting.taskTypeSetting.flow.flowMap.finish.name'),
          value: item.count,
          _origin: item
        });
      });

      return {
        color: colors,
        grid: {
          top: 70,
          bottom: 40,
          left: 80,
          right: 50
        },
        tooltip: {
          trigger: 'none',
          axisPointer: {
            type: 'cross'
          }
        },
        toolbox: {
          feature: {
            saveAsImage: {
              name: t('report.performanceChart.name')
            }
          },
          right: 40
        },
        legend: {
          data:[t('report.callConsultChart.addWorkOrder'), t('task.setting.taskTypeSetting.flow.flowMap.finish.name')],
          top: 5,
          align: 'left'
        },
        xAxis: [
          {
            type: 'category',
            axisTick: {
              alignWithLabel: true
            },
            axisLine: {
              onZero: false,
              lineStyle: {
                color: colors[1]
              }
            },
            axisPointer: {
              label: {
                formatter (params) {
                  return `${t('task.setting.taskTypeSetting.flow.flowMap.finish.name')}  ${ params.value }：${ params.seriesData[0].data.value }${t('account.unitPiece')}`;
                }
              }
            },
            data: created_xAxis
          },
          {
            type: 'category',
            axisTick: {
              alignWithLabel: true
            },
            axisLine: {
              onZero: false,
              lineStyle: {
                color: colors[0]
              }
            },
            axisPointer: {
              label: {
                formatter (params) {
                  return `${t('report.callConsultChart.addWorkOrder')}  ${ params.value }：${ params.seriesData[0].data.value }${t('account.unitPiece')}`;
                }
              }
            },
            data: completed_xAxis
          }
        ],
        yAxis: [{
          type: 'value'
        }],
        series: [
          {
            name:t('report.callConsultChart.addWorkOrder'),
            type:'line',
            smooth: true,
            data: created_data,
            xAxisIndex: [1],
            itemStyle: { normal: {label : {show: true}}}
          },
          {
            name:t('task.setting.taskTypeSetting.flow.flowMap.finish.name'),
            type:'line',
            smooth: true,
            data: completed_data,
            xAxisIndex: [0],
            itemStyle: { normal: {label : {show: true}}}
          }
        ]
      }
    },
    fetchTrendData(){
      let params = {
        timeStart: this.trendStartTime,
        timeEnd: this.trendEndTime,
        tagId: this.teamId
      }
      return http.get('/api/report/outside/stats/plan/trend', params)
    },
    async renderTable(day, state){
      try {
        let instance = this.$loading.show(this.$el)
        let data = await this.fetchTableData(day, state);
        instance.hide();

        this.$nextTick(() => {
          this.tableData = data;
          this.showTable = true;
        })
      } catch (error) {
        console.log(error)
      }
    },
    fetchTableData(day, state){
      let params = {
        timeStart: +dayTimeStart(day),
        timeEnd: +dayTimeEnd(day),
        tagId: this.teamId,
        state
      }

      return http.post('/api/report/outside/stats/plan/trendDetail', params)
    },
    buildColumns(){
      return [
        {
          label: t('common.base.serialNumber'),
          field: 'taskNo',
          width: 140,
          render: (h, row, field) =>{
            let data = {
              attrs: {
                href: `/task/view/${row.taskId}`
              },
              on: {
                click: event => {
                  event.preventDefault();
                  let fromId = window.frameElement.getAttribute('id');
                  // this.$platform.openTab({
                  //   id: `taskView_${ row.taskId}`, 
                  //   title: `工单${row.taskNo}`,
                  //   close: true, 
                  //   url: `/task/view/${ row.taskId}`,
                  //   fromId
                  // });
                  openAccurateTab({
                    type: PageRoutesTypeEnum.PageTaskView,
                    key: row.taskId,
                    titleKey: row.taskNo,
                    fromId
                  })
                }
              }
            };
            return h('a', data, [row.taskNo])
          }
        },
        {
          label: t('common.task.taskType'),
          field: 'templateName',
          width:120
        },
        {
          label: t('common.base.customer'),
          field: 'customerName'
        },
        {
          label: t('common.base.status'),
          field: 'state',
          width: 100,
          template: (row, field) => {
            let state = row.state;
            let stateValue = TaskStateEnum.getValue(state);

            return `<span class="stats-badge" style="background-color:${TaskStateEnum.getColor(stateValue)};">${state}</span>`;
          }
        },
        {
          label: t('common.fields.executorUser.displayName'),
          field: 'executorName',
          width: 150,
          render: (h, row, field) => {
            return (<div>{isOpenData && row.executorStaffId ? <open-data type="userName" openid={row.executorStaffId}></open-data> : row.executorName}</div>)
          }
        },
        {
          label: t('common.fields.createUser.displayName'),
          field: 'createUserName',
          width: 150,
          render: (h, row, field) => {
            return (<div>{isOpenData && row.createUserStaffId ? <open-data type="userName" openid={row.createUserStaffId}></open-data> : row.createUserName}</div>)
          }
        }
      ]
    },
    datePicker(data) {
      // 初始化趋势图
      this.initTrend(data[0], data[1]);
    }
  },
  mounted(){
    // let initData = _init_data || {};
    // this.teams = initData.teams || [];

    window.onresize = _.debounce(function(){
      trend.resize();
    }, 200)
  }
}
</script>

<style lang="scss">
.stats-trend-table-wrap{
  padding: 10px 50px 10px 80px;
}

.stats-trend-table-bar{
  display: flex;
  flex-flow: row nowrap;
  margin-bottom: 5px;

  h5{
    margin: 0;
    font-size: 14px;
    line-height: 24px;
    flex: 1;
  }

  .btn-sm{
    padding: 2px 20px;
  }

}
.stats-panel-trend {
  .base-table-cell {
    height: auto;
  }
}

</style>
